import {MsgUtils} from "@/base/ts/utils/MsgUtils.ts";
import {stores} from "@/base/stores";
import router from "@/base/router";
import AuthApi, {LoginDto, LoginVo} from "@/base/ts/api/biz/AuthApi.ts";


//登录过期
export function loginDue() {
  MsgUtils.alert(() => {
    logout();
  }, "关闭或点击确认将重新登录", "登录过期提醒")
}

//退出登录
export function logout() {
  //清除缓存的用户信息
  const storeArr: any[] = [stores().user]
  storeArr.forEach(store => {
    Object.getOwnPropertyNames(store.$state).forEach((storeKey: string) => {
      store[storeKey] = undefined;
    })
  })
  router.replace(stores().cache.loginPage);
}

//登录
export function login(loginVo: LoginVo) {
  AuthApi.login(loginVo)
    .start(() => MsgUtils.loading())
    .end(() => MsgUtils.loading_close())
    .success(result => {
      loginEnd(result.data!);
    }).request()
}

//登录完成
export function loginEnd(loginDto: LoginDto) {
  stores().user.userInfo = loginDto;
  router.replace('/')
}

//刷新用户信息
export function refreshUserInfo() {
  if (!stores().user.userInfo?.token) {
    return;
  }
  AuthApi.refreshUserInfo()
    .start(() => MsgUtils.loading())
    .end(() => MsgUtils.loading_close())
    .success(result => {
      stores().user.userInfo = result.data;
    }).request()
}

//清除缓存
export function clearCache() {
  //清除缓存的用户信息
  const storeArr: any[] = [stores().cache,stores().theme];
  storeArr.forEach(store => {
    Object.getOwnPropertyNames(store.$state).forEach((storeKey: string) => {
      store[storeKey] = undefined;
    })
  })
  //刷新页面
  window.location.reload();
}

//获取当前路由对应的菜单
export function getMenuByPath(path: string) {
  return stores().user.userInfo?.menuList?.filter(menu => menu.path === path)[0];
}
//根据ID获取菜单
export function getMenuById(id: string) {
  return stores().user.userInfo?.menuList?.filter(menu => menu.id === id)[0];
}
